package definite.Guide.Book.JRadioButton;

import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;
import javax.swing.event.ChangeListener;

public class JRadioButtonUtils {

	private JRadioButtonUtils() {
		// private constructor so can't create instance
	}

	public static Container createRadioButtonGrouping(String elements[],
			String title, ActionListener actionListener) {
		return createRadioButtonGrouping(elements, title, actionListener, null,
				null);
	}

	public static Container createRadioButtonGrouping(String elements[],
			String title, ActionListener actionListener,
			ItemListener itemListener, ChangeListener changeListener) {
		JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(0, 1));
		if (title != null) {
			Border border = BorderFactory.createTitledBorder(title);
			panel.setBorder(border);
		}

		JRadioButton radioButton;
		ButtonGroup radioGroup = new ButtonGroup();
		for (int i = 0; i < elements.length; i++) {
			radioButton = new JRadioButton(elements[i]);

			if (actionListener != null)
				radioButton.addActionListener(actionListener);
			if (itemListener != null)
				radioButton.addItemListener(itemListener);
			if (changeListener != null)
				radioButton.addChangeListener(changeListener);

			radioGroup.add(radioButton);
			panel.add(radioButton);
		}

		return panel;
	}

	public static Enumeration<String> getSelectedItem(Container container) {
		Vector<String> selectList = new Vector<>();
		Component[] components = container.getComponents();
		for (int i = 0; i < components.length; i++)
			if (components[i] instanceof AbstractButton) {
				AbstractButton button = (AbstractButton) components[i];
				if (button.isSelected())
					selectList.addElement(button.getText());
			}

		return selectList.elements();
	}
}
